package com.cloud.elm.service.impl;

import com.cloud.elm.mapper.CartMapper;
import com.cloud.elm.mapper.FoodMapper;
import com.cloud.elm.mapper.OrderDetailetMapper;
import com.cloud.elm.mapper.OrdersMapper;
import com.cloud.elm.po.Cart;
import com.cloud.elm.po.Food;
import com.cloud.elm.po.OrderDetailet;
import com.cloud.elm.po.Orders;
import com.cloud.elm.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private FoodMapper foodMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;

    @Override
	@Transactional
	public int createOrders(Orders orders) {
		//1、查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);

		//2、创建订单（返回生成的订单编号）
//		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();

		//3、批量添加订单明细
		for(Cart c : cartList) {
			Integer foodId = c.getFoodId();
			Food food = foodMapper.getFoodById(foodId);

			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodName(food.getFoodName());
			od.setFoodPrice(food.getFoodPrice());
			od.setQuantity(c.getQuantity());

			orderDetailetMapper.saveOrderDetailet(od);
		}

		//4、从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);

		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}

	@Override
	public void updateOrderState(Integer state, Integer orderId) {
		ordersMapper.updateOrderState(state, orderId);
	}

	@Override
	public List<Orders> listOrdersByBusinessId(String businessId) {
		return ordersMapper.listOrdersByBusinessId(businessId);
	}

	@Override
	public List<OrderDetailet> getOrderDetailetByOrderId(Integer orderId) {
		return ordersMapper.getOrderDetailetByOrderId(orderId);
	}

	@Override
	public void cancelOrder(Integer orderId) {
		ordersMapper.delOrderById(orderId);
		orderDetailetMapper.delOdById(orderId);
	}

	@Override
	public Integer getOrderId(String userId, String businessId, String orderDate) {
		return ordersMapper.getOrderId(userId, businessId, orderDate);
	}
}
